package com.otod.base.support.spring.mybatis;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Properties;

import org.apache.ibatis.executor.ErrorContext;
import org.apache.ibatis.executor.ExecutorException;
import org.apache.ibatis.executor.statement.BaseStatementHandler;
import org.apache.ibatis.executor.statement.RoutingStatementHandler;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.ParameterMode;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.property.PropertyTokenizer;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.type.TypeHandler;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.otod.base.support.spring.mybatis.paginator.dialect.IDialect;
import com.otod.commons.entity.Page;
import com.otod.commons.utils.ReflectHelper;

//import org.apache.ibatis.scripting.xmltags.ForEachSqlNode;


/**
 * 实现分页
 *
 * @author jqiu
 * @ClassName: PageInterceptor
 * @date 2014-3-9 上午10:14:49
 */
@Intercepts({@Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class})})
public class PageInterceptor implements Interceptor {
    //是在mybatis的核心配置文件mybatis-config.xml中配置的
    private String dialectClass;

    protected Logger logger = LoggerFactory.getLogger(getClass());

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if (!(invocation.getTarget() instanceof RoutingStatementHandler)) {
            return invocation.proceed();
        }

        RoutingStatementHandler statementHandler = (RoutingStatementHandler) invocation.getTarget();
        BaseStatementHandler handler = (BaseStatementHandler) ReflectHelper.getValueByFieldName(statementHandler, "delegate");
        MappedStatement ms = (MappedStatement) ReflectHelper.getValueByFieldName(handler, "mappedStatement");


        BoundSql boundSql = handler.getBoundSql();
        Object paramObject = boundSql.getParameterObject();

        if (paramObject instanceof HashMap) {
//            Map map = (Map) paramObject;
//            Iterator keys = map.entrySet().iterator();
//            Page page = null;
//            for (Iterator iterator = keys; iterator.hasNext(); ) {
//                Map.Entry<String, Object> mapPage = (Map.Entry<String, Object>) iterator.next();
//                if (mapPage.getValue() instanceof Page) {
//                    page = (Page) mapPage.getValue();
//                    break;
//                }
//            }
        	Page page = null;
        	
            HashMap<String,Object> map = (HashMap) paramObject;    
            if ((map.containsKey(Page.PAGE_KEY))) {
            	page = (Page) map.get(Page.PAGE_KEY);
			}
//            if ((map.containsKey(Page.PAGE_PARAM))) {
//            	addParamters(boundSql);
//            }
			
			
            if (page != null) {
            	IDialect dialect = this.getDialect();
            	
            	int startIndex = page.getStartIndex();
            	int pageSize = page.getPageSize();
            	
            	String pageSql = dialect.getPagedString(boundSql.getSql(), startIndex, pageSize);
                
                int totalCount = queryTotal(dialect, invocation, ms, boundSql, map);
                page.setiTotalRecords(totalCount);
                if (totalCount < 1) {
                     page.setiTotalDisplayRecords(0);
                } else {
                	if(totalCount<=startIndex){
                		page.setiTotalDisplayRecords(0);
                	}else{
                		int ret = totalCount-startIndex;
                		if(ret >= pageSize){					//如果为最后一页，且不足pageSize数时,实际记录数为 总记录数-开始索引数（0开始）
                			page.setiTotalDisplayRecords(pageSize);
                		}else{
                			page.setiTotalDisplayRecords(ret);			
                		}
                	}
                }
                this.logger.debug(pageSql);
                ReflectHelper.setValueByFieldName(boundSql, "sql", pageSql);//将分页sql语句反射回BoundSql.
            }
        }

        return invocation.proceed();

    }

    
    /**
     * 计算总页数
     * @param dialect
     * @param ivk
     * @param ms
     * @param boundSql
     * @param param
     * @return
     * @throws Throwable
     */
    private int queryTotal(IDialect dialect,Invocation ivk, MappedStatement ms, BoundSql boundSql,HashMap param) throws Throwable {
    	Connection conn = (Connection) ivk.getArgs()[0];

        BoundSql countBS = null;
        
        if(param.containsKey(Page.PAGE_COUNT)){
			MappedStatement sqlCustom  = ms.getConfiguration().getMappedStatement((String)param.get(Page.PAGE_COUNT));
			countBS = sqlCustom.getBoundSql(param);
		}
        
        if(countBS == null){
            String countSql = dialect.getCountString(boundSql.getSql());
            // 获取记录总数
            countBS = new BoundSql(ms.getConfiguration(), countSql, boundSql.getParameterMappings(), param);
        }
        
        PreparedStatement countStmt = conn.prepareStatement(countBS.getSql());
        this.setParameters(countStmt, ms, countBS, param);
        ResultSet rs = countStmt.executeQuery();
        int count = 0;
        if (rs.next()) {
            count = rs.getInt(1);
        }
        rs.close();
        countStmt.close();

        return count;
    }



    /*
     * <p>Title: plugin</p>
     * <p>Description: </p>
     * @param arg0
     * @return
     * @see org.apache.ibatis.plugin.Interceptor#plugin(java.lang.Object)
     */
    @Override
    public Object plugin(Object arg0) {
        return Plugin.wrap(arg0, this);
    }


    /**
     * 对SQL参数(?)设值,参考org.apache.ibatis.executor.parameter.DefaultParameterHandler
     *
     * @param ps
     * @param mappedStatement
     * @param boundSql
     * @param parameterObject
     * @throws SQLException
     */
    private void setParameters(PreparedStatement ps, MappedStatement mappedStatement, BoundSql boundSql, Object parameterObject) throws SQLException {
        ErrorContext.instance().activity("setting parameters").object(mappedStatement.getParameterMap().getId());
        List<ParameterMapping> parameterMappings = boundSql.getParameterMappings();
        if (parameterMappings != null) {
            Configuration configuration = mappedStatement.getConfiguration();
            TypeHandlerRegistry typeHandlerRegistry = configuration.getTypeHandlerRegistry();
            MetaObject metaObject = parameterObject == null ? null : configuration.newMetaObject(parameterObject);
            for (int i = 0; i < parameterMappings.size(); i++) {
                ParameterMapping parameterMapping = parameterMappings.get(i);
                if (parameterMapping.getMode() != ParameterMode.OUT) {
                    Object value;
                    String propertyName = parameterMapping.getProperty();
                    PropertyTokenizer prop = new PropertyTokenizer(propertyName);
                    if (parameterObject == null) {
                        value = null;
                    } else if (typeHandlerRegistry.hasTypeHandler(parameterObject.getClass())) {
                        value = parameterObject;
                    } else if (boundSql.hasAdditionalParameter(propertyName)) {
                        value = boundSql.getAdditionalParameter(propertyName);
                    }/* else if (propertyName.startsWith(ForEachSqlNode.ITEM_PREFIX)&& boundSql.hasAdditionalParameter(prop.getName())) {  
                        value = boundSql.getAdditionalParameter(prop.getName());  
                        if (value != null) {  
                            value = configuration.newMetaObject(value).getValue(propertyName.substring(prop.getName().length()));  
                        }  
                    } */ else {
                        value = metaObject == null ? null : metaObject.getValue(propertyName);
                    }
                    TypeHandler typeHandler = parameterMapping.getTypeHandler();
                    if (typeHandler == null) {
                        throw new ExecutorException("There was no TypeHandler found for parameter " + propertyName + " of statement " + mappedStatement.getId());
                    }
                    typeHandler.setParameter(ps, i + 1, value, parameterMapping.getJdbcType());
                }
            }
        }
    }

    /**
     * 初始化方言
     *
     * @param conn
     */
    private IDialect getDialect() throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException {
        String dialectClass = this.dialectClass;

        Class clz;
        try {
            clz = Class.forName(dialectClass);
        } catch (ClassNotFoundException e) {
            logger.error("初始化方言失败,mybatis-config.xml中的dialectClass所配置的类名不正确【" + dialectClass + "】", e);
            throw e;
        }
        IDialect dialect = (IDialect) clz.newInstance();
        return dialect;
    }

    /**
     * 读取mybatis-config.xml配置文件的信息
     */
    @Override
    public void setProperties(Properties properties) {
        //得到数据库类型
        this.dialectClass = properties.getProperty("dialectClass");
    }

}
